package com.tron.dobest.fastdfs;

import com.google.common.base.Charsets;
import com.tron.dobest.common.TronException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * 描述：
 *
 * @author TRON
 * @since 2020-03-23
 */
@RestController
@Api(tags = "文件管理")
@Slf4j
public class FileController {

    @ApiOperation(value = "文件上传",notes = "文件上传")
    @PostMapping("/file/upload")
    public String fileUpload(@RequestParam("file") MultipartFile file) {
        String path = "";
        try {
            // Get the file and save it somewhere
            path=saveFile(file);
        } catch (Exception e) {
            log.error("upload file failed",e);
            throw new TronException(400, "文件上传失败："+e.getMessage());
        }
        return path;
    }

    @ApiOperation(value = "文件删除",notes = "文件删除")
    @PostMapping("/file/delete")
    public Integer fileDelete(@RequestParam String groupName, @RequestParam String remoteFileName) {
        try {
            FastDFSClient.deleteFile(groupName,remoteFileName);
        } catch (Exception e) {
            log.info("删除文件失败："+e.getMessage());
            return 500;
        }
        return 200;
    }


    @ApiOperation(value = "文件下载",notes = "文件下载")
    @GetMapping("/file/download")
    public void fileDownload(@RequestParam String groupName, @RequestParam String remoteFileName, HttpServletResponse response) {
        InputStream inputStream = FastDFSClient.downFile(groupName, remoteFileName);
        String fileExt = FastDFSClient.getFileExt(groupName, remoteFileName);
        try {
            //设置响应头
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("fileName"+fileExt, Charsets.UTF_8.toString()));
            //获取输出流
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buff = new byte[1024];
            int read = 0;
            while ((read = inputStream.read(buff)) != -1) {
                //将文件写入响应
                outputStream.write(buff, 0, read);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String saveFile(MultipartFile multipartFile) throws IOException {
        String[] fileAbsolutePath={};
        String fileName=multipartFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        byte[] fileBuff = null;
        InputStream inputStream=multipartFile.getInputStream();
        if(inputStream!=null){
            int len1 = inputStream.available();
            fileBuff = new byte[len1];
            inputStream.read(fileBuff);
        }
        inputStream.close();
        FastDFSFile file = new FastDFSFile();
        file.setName(fileName);
        file.setContent(fileBuff);
        file.setExt(ext);
        file.setAuthor("tron");
        try {
            fileAbsolutePath = FastDFSClient.upload(file);  //upload to fastdfs
        } catch (Exception e) {
            log.error("upload file Exception!",e);
        }
        if (fileAbsolutePath==null) {
            log.error("upload file failed,please upload again!");
        }
        String path=FastDFSClient.getTrackerUrl()+fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
        return path;
    }
}
